package com.iotechn.unimall.biz.service.dict;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.core.Const;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.component.CacheComponent;
import com.iotechn.unimall.data.domain.DictDO;
import com.iotechn.unimall.data.mapper.DictMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by rize on 2019/7/12.
 */
@Service
public class DictBizService {

    @Autowired
    private DictMapper dictMapper;

    @Autowired
    private CacheComponent cacheComponent;

    private static final String CA_DICT_HASH = "CA_DICT_HASH";
    private static final String DICT_ = "DICT_";

    public static final String CA_DICT_MAP = "CA_DICT_MAP";


    public Map<String,List<DictDO>> getAllDictList() throws ServiceException{
        Map<String,List<DictDO>> dictDOListFormCache = cacheComponent.getObj(CA_DICT_MAP, Map.class);
        if (dictDOListFormCache != null) {
            return dictDOListFormCache;
        }

        Wrapper<DictDO> wrapper = new EntityWrapper<DictDO>();
        List<DictDO> DictDOs = dictMapper.selectList(wrapper.orderBy("datatype"));
        Map<String,List<DictDO>> map = new HashMap();
        for(DictDO dictDO:DictDOs){

            List list = map.get(dictDO.getDatatype());
            if(list != null){
                list.add(dictDO);
            }else{
                list = new ArrayList();
                list.add(dictDO);
                map.put(dictDO.getDatatype(),list);
            }


        }

        //放入缓存
        cacheComponent.putObj(CA_DICT_MAP, map, Const.CACHE_ONE_DAY);
        return map;
    }
    public List<DictDO> dicListByDatatype(String datatype) throws ServiceException {

        List<DictDO> objList = cacheComponent.getObjList(DICT_ + datatype, DictDO.class);
        if (objList != null) {
            return objList;
        }

        Wrapper<DictDO> wrapper = new EntityWrapper<DictDO>();
        wrapper.eq("dataType", datatype);

        List<DictDO> DictDOs = dictMapper.selectList(wrapper);

        cacheComponent.putHashObj(CA_DICT_HASH,DICT_ + datatype, DictDOs, 60 * 60);
        return DictDOs;
    }

    public void clearDictCache(String datatype) {

        cacheComponent.del(CA_DICT_MAP);

        cacheComponent.del(DICT_ + datatype);

    }
}
